package com.kchouse.homepage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.HomepageFragment;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.CashCouponItem;
import com.kchouse.bean.CouponItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.mine.LoginPhoneActivity;
import com.kchouse.union.MerchantDetailsActivity;
import com.squareup.picasso.Picasso;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class CouponDetailsActivity extends BaseActivity implements View.OnClickListener {

    private CouponDetailsActivity mContent;
    private Intent intent;
    private String coupon;
    private TextView tv_title;
    private ImageView iv_back;
    private View ll_time;
    private CashCouponItem data;
    private TextView tv_detail;
    private TextView tv_type;
    private TextView tv_num;
    private Button bt_item;
    private ImageView iv_icon;
    private boolean ispost;//是否可领取
    private CouponItem data2;
    private TextView tv_couponlimit;
    private Button bt_item2;
    private TextView tv_buy;
    private View ll_merchant;
    private View ll_bottom;
    private boolean isfocus=false;//是否关注
    private ImageView iv_focus;
    private View ll_focus;
    private boolean isLogin = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coupon_details);

        mContent = this;
        intiData();
//        intiView();
    }

    private void intiData() {
        intent = getIntent();
        coupon = intent.getStringExtra("coupon");//判断是现金券还是优惠券

        if (coupon.equals("现金券")) {
            data = (CashCouponItem) intent.getSerializableExtra("data");
            GetCheckCashCoupon();
            intiView();
        } else {
            data2 = (CouponItem) intent.getSerializableExtra("data");
            GetCheckCoupon();
            intiView2();
        }
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(coupon);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        ll_time = findViewById(R.id.ll_time);
//        if (coupon.equals("现金券")) {
        ll_time.setVisibility(View.GONE);
//        } else {
////            data2.endTime
//        }
        iv_icon = (ImageView) findViewById(R.id.iv_icon);
        Picasso.with(mContent).load(data.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_icon);
        tv_detail = (TextView) findViewById(R.id.tv_detail);
        tv_detail.setText(data.getCashRuleDesc());
        tv_type = (TextView) findViewById(R.id.tv_type);
        tv_type.setText(coupon);
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_num.setText(data.getNum() + "");
        ll_bottom =  findViewById(R.id.ll_bottom);
        bt_item = (Button) findViewById(R.id.bt_item);
        bt_item.setOnClickListener(this);
        bt_item.setVisibility(View.VISIBLE);
        ll_bottom.setVisibility(View.GONE);

    }

    private void intiView2() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(coupon);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        tv_couponlimit = (TextView) findViewById(R.id.tv_couponlimit);
        tv_couponlimit.setText("至" + data2.getEndTime());
        iv_icon = (ImageView) findViewById(R.id.iv_icon);
        Picasso.with(mContent).load(data2.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_icon);
        tv_detail = (TextView) findViewById(R.id.tv_detail);
        tv_detail.setText(data2.getDetail());
        tv_type = (TextView) findViewById(R.id.tv_type);
        tv_type.setText(coupon);
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_num.setText(data2.getInventory() + "");
        tv_buy = (TextView) findViewById(R.id.tv_buy);
        tv_buy.setOnClickListener(this);
        ll_merchant =  findViewById(R.id.ll_merchant);
        ll_merchant.setOnClickListener(this);
        bt_item = (Button) findViewById(R.id.bt_item);
        bt_item.setVisibility(View.GONE);
        iv_focus = (ImageView) findViewById(R.id.iv_focus);
        ll_focus = findViewById(R.id.ll_focus);
        ll_focus.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_buy:
                if (checkLogin()) return;
                PostCoupon();
                break;
            case R.id.ll_merchant:
                if (checkLogin()) return;
                intent.putExtra("Merchantid", data2.getMerchantId());
                intent.setClass(mContent, MerchantDetailsActivity.class);
                startActivity(intent);
                break;
            case R.id.bt_item:
                if (checkLogin()) return;
                PostCashCoupon();
                break;
            case R.id.ll_focus:
                if (checkLogin()) return;
                if (isfocus) {
                    DelFocus();
                } else {
                    PostAddFocus();
                }
                break;
        }
    }

    /**
     * 校验登录状态
     *
     * @return
     */
    private boolean checkLogin() {
        // 如果未登录都进入登录界面
        if (!isLogin) {
            intent.setClass(mContent, LoginPhoneActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }





    /**
     * 取消关注
     */
    private void DelFocus() {
        String url = API.DelFocus + MainActivity.userid + "/" + data2.getMerchantId();
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("userId", MainActivity.userid);
        params.addFormDataPart("merchantId", data2.getMerchantId());
        params.addHeader("token", MainActivity.token);//添加header信息
        HttpRequest.delete(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    iv_focus.setImageResource(R.mipmap.ic_focus_off);
                    isfocus = false;
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    if (data.getString("code").equals("401")) {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 添加关注
     */
    private void PostAddFocus() {
        String url = API.PostAddFocus;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        JSONObject ob = new JSONObject();
        ob.put("userId", MainActivity.userid);
        ob.put("merchantId", data2.getMerchantId());
        params.addHeader("token", MainActivity.token);//添加header信息
        params.applicationJson(ob);


        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    iv_focus.setImageResource(R.mipmap.ic_focus_on);
                    isfocus = true;
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    if (data.getString("code").equals("401")) {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }



    /**
     * 领取优惠券
     */
    private void PostCoupon() {
        String url = API.PostCoupon + data2.getId() + "/" + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("templateId", data2.getId());
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
//                    String datastr = json.getString("data");
                    ToastUtils.getInstanc(mContent).showToast("领取成功，请移步到我的卡券查看数量");
                    finish();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    if (data.getString("code").equals("401")) {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                        finish();
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 领取现金券
     */
    private void PostCashCoupon() {
        String url = API.PostCashCoupons + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("token", MineFragment.userid);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
//                    data = JSONObject.parseObject(datastr, CashCouponItem.class);
//                    Picasso.with(getActivity()).load(data.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_icon);
//                    tv_name.setText(data.getCashTemplateName());
//                    tv_num.setText("剩余数量："+data.getNum());
                    ToastUtils.getInstanc(mContent).showToast("领取成功，请移步到我的卡券查看数量");
                    finish();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 是否可以领取优惠券
     */
    private void GetCheckCoupon() {
        String url = API.GetCheckCoupons + data2.getId() + "/" + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("templateId", data2.getId());
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    ispost = json.getBooleanValue("data");

                    if (ispost) {
                        tv_buy.setText("立即领取");
                        tv_buy.setEnabled(true);
//                        bt_item.setBackgroundResource(R.drawable.bg_corners_blue_btn);
                    } else {
                        tv_buy.setText("已领取");
                        tv_buy.setEnabled(false);
//                        bt_item.setBackgroundResource(R.drawable.bg_corners_blue2_btn);
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    if (data.getString("code").equals("401")) {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                        finish();
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 是否可以领取现金券
     */
    private void GetCheckCashCoupon() {
        String url = API.GetCheckCashCoupons + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("token", MineFragment.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    ispost = json.getBooleanValue("data");

                    if (ispost) {
                        bt_item.setText("领取");
                        bt_item.setEnabled(true);
                        bt_item.setBackgroundResource(R.drawable.bg_corners_blue_btn);
                    } else {
                        bt_item.setText("已领取");
                        bt_item.setEnabled(false);
                        bt_item.setBackgroundResource(R.drawable.bg_corners_blue2_btn);
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    if (data.getString("code").equals("401")) {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                        finish();
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!coupon.equals("现金券")) {
            GetCheckFocus();
        }

        if (!MainActivity.mobile.equals("")) {
            isLogin = true;
        } else {
            isLogin = false;
        }
    }

    /**
     * 校验是否关注
     */
    private void GetCheckFocus() {
        String url = API.GetCheckFocus + MainActivity.userid + "/" + data2.getMerchantId();
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("userId", MainActivity.userid);
        params.addFormDataPart("merchantId", data2.getId());
        params.addHeader("token", MainActivity.token);//添加header信息

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    isfocus = json.getBooleanValue("data");
                    if (isfocus) {
                        iv_focus.setImageResource(R.mipmap.ic_focus_on);
                    } else {
                        iv_focus.setImageResource(R.mipmap.ic_focus_off);
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    if (data.getString("code").equals("401")) {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });

    }
}
